package com.youmingxing.adpter.selfInfo;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.youmingxing.R;
import com.youmingxing.activity.ContentDetailActivity;
import com.youmingxing.activity.selfInfo.ChooseMyAuditionsActivity;
import com.youmingxing.activity.selfInfo.MyAuditionGoingActivity;
import com.youmingxing.activity.selfInfo.PersonalInfoActivity;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.HighLight;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.utils.Tools;
import com.youmingxing.view.DialogManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * @author evilyin(ChenZhixi)
 * @since 15/9/4
 */
public class ChooseAuditionsListAdapter extends BaseAdapter {

    // 存放选中作品id
    public static int selectedAuditionsId = -1;
    public static CheckBox mCheckBox;

    private List<Content> mList = new ArrayList<>();
    private LayoutInflater inflater;
    private Context context;

    public ChooseAuditionsListAdapter(Context ctx) {
        inflater = LayoutInflater.from(ctx);
        this.context = ctx;
    }


    public void setData(List<Content> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        if (mList == null) {
            mList = list;
        } else {
            mList.clear();
            mList.addAll(list);
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        ContentListener listener = new ContentListener(position);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item_choose_auditions, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.content_image);
            holder.play = (ImageView) convertView.findViewById(R.id.content_video_play);
            holder.userHeadImg = (ImageView) convertView.findViewById(R.id.content_avatar);
            holder.title = (TextView) convertView.findViewById(R.id.content_title);
            holder.repostNumber = (TextView) convertView.findViewById(R.id.content_repost_number);
            holder.likeNumber = (TextView) convertView.findViewById(R.id.content_like_number);
            holder.commentNumber = (TextView) convertView.findViewById(R.id.content_comment_number);
            holder.actorName = (TextView) convertView.findViewById(R.id.content_actor_name);
            holder.isVerified = (ImageView) convertView.findViewById(R.id.is_auth);
            holder.cbAuditions = (CheckBox) convertView.findViewById(R.id.cb_auditions);
            holder.notPassView = convertView.findViewById(R.id.not_passed);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Content thisContent = mList.get(position);
        if (thisContent.getType() == 1) {
            holder.play.setVisibility(View.GONE);
            Glide.with(context.getApplicationContext()).load(thisContent.getThumbnail()).placeholder(R
                    .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder
                    .imageView);
        } else if (thisContent.getType() == 2) {
            holder.play.setVisibility(View.VISIBLE);
            if (!thisContent.getThumbnail().equals("")) {
                Glide.with(context).load(thisContent.getThumbnail()).placeholder(R
                        .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder
                        .imageView);
            } else {
                holder.imageView.setImageResource(R.drawable.default_16_9);
            }
            holder.play.setOnClickListener(listener);
        }
        holder.imageView.setOnClickListener(listener);

        holder.title.setOnClickListener(listener);
        holder.repostNumber.setText(Tools.toK(thisContent.getShare_num()));
        holder.likeNumber.setText(Tools.toK(thisContent.getThumbsup_num()));
        holder.commentNumber.setText(Tools.toK(thisContent.getComment_num()));
        holder.actorName.setText(thisContent.getU_name());
        holder.actorName.setOnClickListener(listener);
        if (!thisContent.getU_headimg().equals("")) {
            Glide.with(context).load(thisContent.getU_headimg()).placeholder(R.drawable.default_avatar)
                    .bitmapTransform(new
                            CropCircleTransformation(context)).thumbnail(0.3f).into(holder.userHeadImg);
        }
        holder.userHeadImg.setOnClickListener(listener);

        //认证
        if (thisContent.isU_auth()) {
            Drawable auth = context.getResources().getDrawable(R.mipmap.identification);
            holder.actorName.setCompoundDrawablesWithIntrinsicBounds(null, null, auth, null);
        } //官方
        if (thisContent.user_type.equals("11")) {
            Drawable auth = context.getResources().getDrawable(R.mipmap.gf);
            holder.actorName.setCompoundDrawablesWithIntrinsicBounds(null, null, auth, null);
        }
        if (!thisContent.isU_auth() && thisContent.user_type.equals("10")) {
            holder.actorName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }


        //是否审核通过
        if (thisContent.status == 2) {
            holder.notPassView.setVisibility(View.VISIBLE);
        } else {
            holder.notPassView.setVisibility(View.GONE);
        }
        //活动内容
        SpannableString spStr = new SpannableString(thisContent.title);
        for (int i = 0; i < thisContent.highLights.size(); i++) {
            final HighLight highLight = thisContent.highLights.get(i);
            if (thisContent.title.contains(highLight.topic)) {
                int start = thisContent.title.indexOf(highLight.topic);
                int end = start + highLight.topic.length();
                spStr.setSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff507daf);       //设置文件颜色
                        ds.setUnderlineText(false);      //设置下划线
                    }

                    @Override
                    public void onClick(View widget) {
                        highLight.action.jump(context);
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        holder.title.setText(spStr);
        holder.title.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
        holder.cbAuditions.setTag(thisContent.getId());
        holder.cbAuditions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox box = (CheckBox) v;
                int update_id = Integer.parseInt(box.getTag().toString());
                if (selectedAuditionsId == -1) {
                    if (box.isChecked()) {
                        mCheckBox = box;
                        selectedAuditionsId = update_id;
                    } else {
                        mCheckBox = null;
                        selectedAuditionsId = -1;
                    }
                } else {
                    if (box.equals(mCheckBox)) {
                        selectedAuditionsId = -1;
                        mCheckBox = null;
                        box.setChecked(false);
                    }else {
                        box.setChecked(false);
                        Toast.makeText(context, "只能选择一个作品置顶", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        return convertView;
    }

    private class ViewHolder {
        ImageView imageView;
        ImageView play;
        ImageView userHeadImg;
        TextView title;
        TextView repostNumber;
        TextView likeNumber;
        TextView commentNumber;
        TextView actorName;
        ImageView isVerified;
        CheckBox cbAuditions;
        View notPassView;
    }

    private class ContentListener implements View.OnClickListener {

        private int position;

        public ContentListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            final Intent intent;
            final Content content = mList.get(position);
            switch (v.getId()) {
                case R.id.content_image:
                case R.id.content_title:
                    if (content.status != 2) {
                        intent = new Intent(context, ContentDetailActivity.class);
                        intent.putExtra("content_id", content.getId());
                        context.startActivity(intent);
                    }
                    break;
                case R.id.content_video_play:
                    AccountApi.getVedioSign(new BaseJsonHandler(context) {
                        @Override
                        public void onSuccessWithData(JSONObject response) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            String url = mList.get(position).getUrl() + "?sign=" + response.optJSONObject
                                    ("data")
                                    .optString("sign");
                            intent.setDataAndType(Uri.parse(url), "video/*");
                            context.startActivity(intent);
                        }
                    });

                    break;
                case R.id.content_avatar:
                case R.id.content_actor_name:
                    intent = new Intent(context, PersonalInfoActivity.class);
                    intent.putExtra("u_id", mList.get(position).getU_id());
                    context.startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    }
}
